package com.carlinfo.stu_ques.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil
{
	private String dateTimePattern = "yyyy-MM-dd HH:mm:ss";
	private String datePattern = "yyyy-MM-dd";

	/**
	 * 将Date变成有格式的字符串
	 * 
	 * @param date
	 * @return
	 *
	 */
	public String dateToStr(Date date)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(this.datePattern);
		return sdf.format(date);
	}

	public String dateToStr(Date date, String pattern)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}

	/**
	 * 将Date变成有格式的字符串
	 * 
	 * @param
	 * @return
	 *
	 */
	public String dateTimeToStr(Date date)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(this.dateTimePattern);
		return sdf.format(date);
	}

	public Date strToDate(String dateStr)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(this.datePattern);
		try
		{
			return sdf.parse(dateStr);
		} catch (ParseException e)
		{
			// e.printStackTrace();
			System.out.println("===时间格式有问题,会变成当前时间===");
		}
		return new Date();
	}

	public Date strToDateTime(String dateStr, String pattern)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try
		{
			return sdf.parse(dateStr);
		} catch (ParseException e)
		{
			// e.printStackTrace();
			System.out.println("==--时间格式有问题,会变成当前时间--==");
		}
		return new Date();
	}

	public Date strToDateTime(String dateStr)
	{
		SimpleDateFormat sdf = new SimpleDateFormat(this.dateTimePattern);
		try
		{
			/* 将Date变成字符串 */
			return sdf.parse(dateStr);
		} catch (ParseException e)
		{
			e.printStackTrace();
		}
		/* 如果转换失败,为了不报空指针,返回当前时间 */
		return new Date();
	}

	/**
	 * 判断是不是昨天
	 * 
	 * @param nowDate 结束时间
	 * @param oldDate 老时间
	 * 
	 */
	public boolean isyesDay(Date nowDate, Date oldDate)
	{
		Calendar calendar = Calendar.getInstance();
		/* 将nowDate覆盖当前时间 */
		calendar.setTime(nowDate);
		/* 将时分秒清0 */
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		/*
		 * 结束时间 2018-08-02 00:00:00
		 */
		Date edDate = calendar.getTime();
		/* 时间-1 */
		calendar.add(Calendar.DATE, -1);
		Date stDate = calendar.getTime();
		System.out.println(stDate.toLocaleString() + "=====>" + edDate.toLocaleString());
		/*
		 * 判断oldDate>2018-08-01 00:00:00 并且小于2018-08-02 00:00:00
		 */
		return oldDate.after(stDate) && oldDate.before(edDate);
	}

	public static void main(String[] args)
	{
		DateUtil dateUtil = new DateUtil();
		/* 转时间 */
		Date nowDate = dateUtil.strToDateTime("2018-08-08 22:22:22");
		Date oldDate = dateUtil.strToDateTime("2018-08-05 20:22:22");
		boolean flag = dateUtil.isyesDay(nowDate, oldDate);
		System.out.println("====>" + flag);
	}

}
